<template>
    <div class="login">
        <div class="login-weaper">
            <div class="login-right">
                <div class="login-main">
                    <h4 class="login-title">许愿墙后台管理系统</h4>
                    <el-form class="el-form login-form" :model="ruleForm" ref="ruleForm" :rules="rules">
                        <el-form-item style="margin-left: 0px" prop="userName">
                            <el-input type="text" placeholder="请输入账号" prefix-icon="el-icon-user"
                                      v-model="ruleForm.userName" clearable autocomplete="off">
                            </el-input>
                        </el-form-item>
                        <el-form-item style="margin-left: 0px" prop="password">
                            <el-input type="password" placeholder="请输入密码" prefix-icon="el-icon-lock"
                                      v-model="ruleForm.password" autocomplete="off" :show-password="true">
                            </el-input>
                        </el-form-item>
                        <el-form-item style="margin: 40px 0px 0;display: flex">
                            <el-button type="primary" @click="submitForm('ruleForm')" :loading="submit.loading">
                                登 录
                            </el-button>
                            <el-button type="primary" @click="dialogFormVisible = true" :loading="submit.loading">
                                注 册
                            </el-button>
                        </el-form-item>
                    </el-form>
                </div>
            </div>
        </div>
        <el-dialog title="注册" :visible.sync="dialogFormVisible" top="27vh" width="80%">
            <el-form :model="form" ref="form" :rules="formrules">
                <el-form-item  prop="name">
                    <el-input placeholder="请输入您的姓名" v-model="form.name" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item prop="userName">
                    <el-input placeholder="请输入您的账号名" v-model="form.userName" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item  prop="password">
                    <el-input placeholder="请输入您的密码" v-model="form.password" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="resubmit('form')">确 定</el-button>
            </div>
        </el-dialog>
        <div class="vue-particles">
            <vue-particles color="#dedede" shapeType="star" linesColor="#dedede" hoverMode="grab" clickMode="push"
                           style="height: 100%"></vue-particles>
        </div>
    </div>
</template>

<script>
    import {Session} from '@/utils/storage';
    import {PrevLoading} from '@/utils/loading.js';

    export default {
        name: 'login',
        data() {
            let checkname = (rule, value, callback) => {
                let reg = /^[a-zA-Z0-9]{5,15}$/
                if (!value) {
                    return callback(new Error('用户名不能为空'));
                } else if (reg.test(value) == false) {
                    callback(new Error("用户名由4-20位字母组成"))
                } else {
                    let data = {
                        username: this.form.userName
                    }
                    data = JSON.stringify(data)
                    // console.log(data)
                    this.$api.post('checkusername', data).then((res) => {
                        if (res.data.id == 1) {
                            callback(new Error("用户名重复"))
                        } else {
                            callback()

                        }
                    })
                }
            };
            return {
                quotations: {},
                isView: false,
                submit: {
                    loading: false,
                },
                ruleForm: {
                    userName: '',
                    password: ''
                },
                form: {
                    userName: '',
                    password: '',
                    name: ''
                },
                dialogFormVisible: false,
                rules: {
                    userName: [
                        {required: true, message: '请输入账号名', trigger: 'blur'},
                    ],
                    password: [
                        {required: true, message: '请输入密码', trigger: 'blur'},
                    ],
                },
                formrules: {
                    userName: [
                        {required: true, validator: checkname, trigger: 'blur'},
                    ],
                    password: [
                        {required: true, message: '请输入密码', trigger: 'blur'},
                    ],
                    name: [
                        {required: true, message: '请输入姓名', trigger: 'blur'},
                    ],
                }
            };
        },
        computed: {
            // 获取布局配置信息
            getThemeConfig() {
                return this.$store.state.themeConfig.themeConfig;
            },
        },
        methods: {
            // 登录按钮点击
            submitForm(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {

                        let data = {
                            password: this.ruleForm.password,
                            username: this.ruleForm.userName
                        }
                        data = JSON.stringify(data)
                        // console.log(data)
                        this.$api.post('login', data).then((res) => {
                            console.log(res)
                            // console.log(res.data)
                            // console.log(res.data.token)
                            if (res.code == 10000) {
                                // this.$message({message: '登录成功', type: 'success'});
                                let defaultAuthPageList = [];
                                // admin 页面权限标识，对应路由 meta.auth
                                let adminAuthPageList = ['admin'];
                                // test 页面权限标识，对应路由 meta.auth
                                let testAuthPageList = ['test'];
                                if (res.data.role == 1) {
                                    defaultAuthPageList = adminAuthPageList;
                                } else {
                                    defaultAuthPageList = testAuthPageList;
                                }
                                const userInfos = {
                                    userName: res.data.username,
                                    name: res.data.name,
                                    last:res.data.lastLoginAt,
                                    role:res.data.role,
                                    time: new Date().getTime(),
                                    authPageList: defaultAuthPageList,
                                };
                                // 存储 token 到浏览器缓存
                                Session.set('token', res.data.token);
                                // 存储用户信息到浏览器缓存
                                Session.set('userInfo', userInfos);
                                // 存储用户信息到vuex
                                this.$store.dispatch('userInfos/setUserInfos', userInfos);
                                PrevLoading.start();
                                window.location.href = `${window.location.origin}${window.location.pathname}`;


                            } else if (res == 'error') {
                                this.$message({
                                    message: '服务器出错啦,稍后重试',
                                    type: 'error'
                                });
                            } else {
                                this.$message({
                                    message: res.msg,
                                    type: 'error'
                                });
                            }
                        })
                    } else {
                        return false;
                    }
                });


            },
            resubmit(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {

                        let data = {
                            password: this.form.password,
                            username: this.form.userName,
                            name: this.form.name
                        }
                        data = JSON.stringify(data)
                        // console.log(data)
                        this.$api.post('register', data).then((res) => {
                            if (res.code == 10000) {
                                this.$message({message: '注册成功', type: 'success'})
                                this.dialogFormVisible = false
                            } else if (res == 'error') {
                                this.$message({
                                    message: '服务器出错啦,稍后重试',
                                    type: 'error'
                                });
                            } else {
                                this.$message({
                                    message: res.msg,
                                    type: 'error'
                                });
                            }
                        })
                    } else {
                        return false;
                    }
                });
            }
        }
    };
</script>

<style scoped lang="scss">
    .login {
        height: 100%;
        width: 100%;
        overflow: hidden;
        display: flex;
        position: relative;

        .vue-particles {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: radial-gradient(ellipse at top left, rgba(105, 155, 200, 1) 0%, rgba(181, 197, 216, 1) 57%);
        }

        .login-weaper {
            margin: auto;
            height: 500px;
            display: flex;
            box-sizing: border-box;
            position: relative;
            z-index: 1;
            border: none;
            box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);

            .login-right {
                width: 491px;
                padding: 20px;
                position: relative;
                align-items: center;
                display: flex;
                background-color: rgba(255, 255, 255, 1);
                border-top-right-radius: 4px;
                border-bottom-right-radius: 4px;

                .login-main {
                    margin: 0 auto;
                    width: 70%;

                    .login-title {
                        color: #333;
                        margin-bottom: 40px;
                        font-weight: 500;
                        font-size: 22px;
                        text-align: center;
                        letter-spacing: 4px;
                    }

                    .login-form {
                        margin: 10px 0;

                        i {
                            color: #333;
                        }

                        .el-form-item {
                            margin-bottom: 20px !important;

                            .login-code {
                                display: flex;
                                align-items: center;
                                justify-content: space-around;
                                margin: 0 0 0 10px;
                                user-select: none;

                                .login-code-img {
                                    margin-top: 2px;
                                    width: 100px;
                                    height: 38px;
                                    border: 1px solid #dcdfe6;
                                    color: #333;
                                    font-size: 14px;
                                    font-weight: 700;
                                    letter-spacing: 5px;
                                    line-height: 38px;
                                    text-indent: 5px;
                                    text-align: center;
                                    cursor: pointer;
                                    transition: all ease 0.2s;
                                    border-radius: 4px;

                                    &:hover {
                                        border-color: #c0c4cc;
                                        transition: all ease 0.2s;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
</style>
